import pygame

# Define some colors
black	= (0, 0, 0)
white	= (255, 255, 255)
green	= (0, 255, 0)
red	= (255, 0, 0)
blue	= (0, 0, 255)

# Initialize the game engine
pygame.init()

pygame.display.set_caption("Title")

# Loop until the user clicks the close button
done = False
clock = pygame.time.Clock()

fps = 60

# Grid values
grid_width = 20
grid_height = 20
grid_margin = 5
# grid_cols = int(width / (grid_width + grid_margin))
# grid_rows = height / (grid_height + grid_margin)
grid_cols = 20
grid_rows = 15

# Set the height and width of the screen
# Adjust according to the grid
width	= grid_cols * (grid_width + grid_margin) + grid_margin
height	= grid_rows * (grid_height + grid_margin) + grid_margin
size 	= [width, height]
screen 	= pygame.display.set_mode(size)

# Create a two dimensional array, to hold the cells
grid = []
for row in range(grid_rows):
	grid.append([])
	for column in range(grid_cols):
		grid[row].append(0)

# When pressed the cells colors go green, then red, then white again

# ----- Main Program Loop -----
while not done:
	# For everything the user does
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			done = True
		if event.type == pygame.MOUSEBUTTONDOWN:
			pos = pygame.mouse.get_pos()
			column = pos[0] // (grid_width + grid_margin)
			row = pos[1] // (grid_height + grid_margin)

			grid[row][column] += 1
			
			if grid[row][column] == 3:
				grid[row][column] = 0

			# print("Click ", pos, "Grid coordinates: ", row, column)

	# Set the screen background
	screen.fill(black)

	# ----- Begin Drawing Something -----

	# Draw the grid
	for row in range(grid_rows):
		for column in range(grid_cols):
			color = white
			if grid[row][column] == 1:
				color = green
			if grid[row][column] == 2:
				color = red
			pygame.draw.rect(screen, color, [(grid_width + grid_margin) * column + grid_margin, (grid_height + grid_margin) * row + grid_margin, grid_width, grid_height])
	
	# ----- End Drawing Something -----

	# Limit to fps frames per second
	clock.tick(fps)

	# Update the screen with what's been drawn
	pygame.display.flip()

# Exit.
pygame.quit()
